package com.dz.core.component.exception;

import com.dz.core.constant.ResCode;
import com.dz.core.dto.ResBody;
import com.google.common.base.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局统一异常处理
 * 返回json
 * Created by lether on 2016/12/8.
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = { NoHandlerFoundException.class })
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResBody noHandlerFoundException(NoHandlerFoundException ex) {
        ex.printStackTrace();
        return new ResBody(ResCode.NOT_FOUND);
    }

    @ExceptionHandler(value = { DzException.class })
    @ResponseStatus(HttpStatus.OK)
    public ResBody resCodeException(DzException ex) {
        ex.printStackTrace();
        if(Strings.isNullOrEmpty(ex.getData())){
            return new ResBody(ex.getCode());
        }else{
            return new ResBody(ex.getCode(),ex.getData());
        }

    }

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResBody exception(Exception ex) {
        ex.printStackTrace();
        if(Strings.isNullOrEmpty(ex.getMessage())){
            return new ResBody(ResCode.SERVER_ERROR);
        }else{
            return new ResBody(ResCode.SERVER_ERROR,ex.getMessage());
        }

    }

}
